use contract_sdk_rust::sim_context;
use contract_sdk_rust::sim_context::*;
use serde_json;
use crate::model;
use model::{Fact};
use contract_sdk_orm::utils::Condition;


// 安装合约时会执行此方法，必须
#[no_mangle]
pub extern "C" fn init_contract() {
    // 安装时的业务逻辑，内容可为空
    sim_context::log("init_contract");
    Fact::create();
}

// 升级合约时会执行此方法，必须
#[no_mangle]
pub extern "C" fn upgrade() {
    // 升级时的业务逻辑，内容可为空
    sim_context::log("upgrade");
    let ctx = &mut sim_context::get_sim_context();
    ctx.ok("upgrade success".as_bytes());
}

#[no_mangle]
pub extern "C" fn save() {
    let ctx = &mut sim_context::get_sim_context();
    // 获取传入参数
    let file_hash = ctx.arg_as_utf8_str("file_hash");
    let file_name = ctx.arg_as_utf8_str("file_name");
    let time_str = ctx.arg_as_utf8_str("time");
    let time: i32 = time_str.parse::<i32>().unwrap();
    let fact = Fact {
        file_hash:file_hash,
        file_name:file_name,
        time:time,
    };
    let r = Fact::insert(&fact);
    match r{
        Ok(i) => ctx.ok(&format!("AffectedRows:{}",i).as_bytes()),
        Err(e) => ctx.error(&format!("ErrorCode:{}",e)),
    };
}

#[no_mangle]
pub extern "C" fn save_all() {
    let ctx = &mut sim_context::get_sim_context();
    // 获取传入参数
    let file_hash = ctx.arg_as_utf8_str("file_hash");
    let file_name = ctx.arg_as_utf8_str("file_name");
    let time_str = ctx.arg_as_utf8_str("time");
    let time: i32 = time_str.parse::<i32>().unwrap();
    let fact = Fact {
        file_hash:file_hash,
        file_name:file_name,
        time:time,
    };
    let mut v = Vec::new();
    v.push(&fact);
    let r = Fact::insert_all(v);
    match r{
        Ok(i) => ctx.ok(&format!("AffectedRows:{}",i).as_bytes()),
        Err(e) => ctx.error(&format!("ErrorCode:{}",e)),
    };
}

#[no_mangle]
pub extern "C" fn query() {
    let ctx = &mut sim_context::get_sim_context();
    let file_hash = ctx.arg_as_utf8_str("file_hash");
    let params = Condition::new("file_hash","=",&file_hash);
    let r = Fact::query(&[params]);
    ctx.ok(serde_json::to_string(&r).expect("Error").as_bytes());
    // ctx.error("hello");
}


#[no_mangle]
pub extern "C" fn update() {
    let ctx = &mut sim_context::get_sim_context();
    let file_hash = ctx.arg_as_utf8_str("file_hash");
    let file_name = ctx.arg_as_utf8_str("file_name");
    let time_str = ctx.arg_as_utf8_str("time");
    let time: i32 = time_str.parse::<i32>().unwrap();
    let fact = Fact {
        file_hash:file_hash,
        file_name:file_name,
        time:time,
    };
    let r = Fact::update(&fact);
    ctx.ok(serde_json::to_string(&r).expect("Error").as_bytes());
}